package phapp.action.system;

import static javacommon.util.Struts2JsonHelper.outJson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javacommon.base.BaseStruts2Action;
import javacommon.jquery.JqueryPageHelper;
import javacommon.jquery.ListRange;
import javacommon.util.StringTool;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.RequestMapping;

import phapp.model.system.Menu;
import phapp.model.system.TreeNode;
import phapp.model.system.TsRoleMenu;
import phapp.service.system.MenuManager;
import phapp.service.system.TsRoleMenuManager;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

/**
 * Title: ts_menu_info Description: 接收前面界面请求,通过json数据格式交互 Action Description:
 * 页面通过Ajax调用Action层,返回JSONO数据 Copyright: Copyright (c) 2012-10 Company:
 * 
 * @author you name
 * @version 1.0
 */

public class MenuAction extends BaseStruts2Action {
	private static int INFO_FLAG_VALID = 1;
	private static int INFO_FLAG_INVALID = 0;

	private static int MENU_ROOT_PARENT_ID = 0; // 显示根目录使用
	private static int MENU_ROOT_ID = 1; // 不显示根目录使用

	private MenuManager menuManager; 
	/** 通过spring自动注入 */
	public void setMenuManager(MenuManager menuManager) {
		this.menuManager = menuManager;
	}
	private TsRoleMenuManager tsRoleMenuManager; 
	/** 通过spring自动注入 */
	public void setTsRoleMenuManager(TsRoleMenuManager menuManager) {
		this.tsRoleMenuManager = menuManager;
	}
	
	/**
	 * jqGrid使用列表 分页查询
	 * 
	 * @throws IOException
	 * @author
	 */
	public void list() throws IOException {
		PageRequest<Map> pr = JqueryPageHelper
				.createPageRequestForJquery(getRequest());
		Page page = menuManager.findByPageRequest(pr);

		List<Menu> Menulist = (List) page.getResult();
		ListRange<Menu> resultList = new ListRange<Menu>();
		resultList.setDataRows(Menulist);
		resultList.setRecords(page.getTotalCount());
		resultList.setRows(page.getPageSize());
		if (page.getTotalCount() % page.getPageSize() > 0) {
			resultList.setTotal(page.getTotalCount() / page.getPageSize() + 1);
		} else {
			resultList.setTotal(page.getTotalCount() / page.getPageSize());
		}
		resultList.setPage(pr.getPageNumber());
		outJson(resultList);
	}

	/**
	 * Menu添加
	 * 
	 * @author
	 * @throws IOException
	 */
	public void save() throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			HttpServletRequest request = getRequest();
			String menuJson = request.getParameter("menuJson");
			if (null != menuJson && !"".equals(menuJson)) {
				JSONObject jsonobject = JSONObject.fromObject(menuJson);
				Menu menuobj = (Menu) JSONObject.toBean(jsonobject, Menu.class);
				menuManager.save(menuobj);
				result.put("success", true);
				result.put("msg", "添加成功!");
			} else {
				result.put("success", false);
				result.put("msg", "添加失败 数据错误!");
			}
		} catch (Exception e) {
			result.put("success", false);
			result.put("msg", "添加失败!");
			e.printStackTrace();
		}
		outJson(result);
	}

	/**
	 * Menu修改
	 * 
	 * @throws IOException
	 * @author
	 */
	public void update() throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			HttpServletRequest request = getRequest();
			String menuJson = request.getParameter("menuJson");
			if (null != menuJson && !"".equals(menuJson)) {
				JSONObject jsonobject = JSONObject.fromObject(menuJson);
				Menu menuobj = (Menu) JSONObject.toBean(jsonobject, Menu.class);

				/** 设置主键值 */
				// menuobj.setId(jsonobject.get("id").toString());
				menuobj.setId(Integer.parseInt(jsonobject.get("id").toString()));

				menuManager.update(menuobj);
				result.put("success", true);
				result.put("msg", "修改成功!");
			} else {
				result.put("success", false);
				result.put("msg", "修改失败 数据错误!");
			}
		} catch (Exception e) {
			result.put("success", false);
			result.put("msg", "修改失败!");
			e.printStackTrace();
		}
		outJson(result);
	}

	/**
	 * Menu删除
	 * 
	 * @throws IOException
	 * @author
	 */
	public void delete() throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			HttpServletRequest request = getRequest();
			String ids = request.getParameter("ids");
			if (null != ids && !"".equals(ids)) {
				Menu menu = new Menu();
				menu.setIdList(StringTool.stringToArray(ids));
				menuManager.removeByIdArry(menu);
				result.put("success", true);
				result.put("msg", "删除成功");
			} else {
				result.put("success", false);
				result.put("msg", "删除失败 数据错误!");
			}
		} catch (Exception e) {
			result.put("success", false);
			result.put("msg", "删除失败!");
			e.printStackTrace();
		}
		outJson(result);
	}

	// 获取菜单：user_id==0时获取全部系统菜单，否则获取指定用户的菜单
	public void getMenuData() throws IOException {
		String strUserID = "";
		JSONObject jsonMenu = null;
		JSONArray menuArray = null;
		Map<String, Object> result = new HashMap<String, Object>();

		try {
			HttpServletRequest request = getRequest();
			String req_param = request.getParameter("req_param");
			if (null != req_param && !"".equals(req_param)) {
				JSONObject jsonobject = JSONObject.fromObject(req_param);
				strUserID = (String) jsonobject.get("user_id");
				if (strUserID == null || strUserID.length() == 0)
					strUserID = "0";
				// System.out.println("MenuAction::getMenuData strUserID - " +
				// strUserID);

				jsonMenu = menuManager.findUserSubmenu(
						Integer.parseInt(strUserID), MENU_ROOT_ID);
				menuArray = (JSONArray) jsonMenu.get("children");
				// System.out.println(menuArray.toString());

				result.put("success", true);
				result.put("msg", menuArray);
			} else {
				result.put("success", false);
				result.put("msg", "获取数据失败！");
			}
		} catch (Exception e) {
			result.put("success", false);
			result.put("msg", "获取数据异常！");
			e.printStackTrace();
		}

		// 如果要返回 字符串 则用 outString(myString);
		outJson(result);
	}
    /**
     * <p>标题: 查询分页数据
     * <p>描述: 
     * @param 
     * @return
     * @throws Exception 
     */
    @RequestMapping("/getComboList") 
    public void  getComboList() throws Exception{
    	Map<String, Object> result = new HashMap<String, Object>();
		List<Menu> dataList =  menuManager.findAll();
		result.put("success", true);
		result.put("list",dataList);
		outJson(result);
    }
	/**
	 * <p> 标题:树
	 * <p> 描述:  
	 * @throws Exception
	 */ 
	public void dataTree() throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();

		List<Menu> dataList = menuManager.findAll();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		HttpServletRequest request = getRequest();
		String roleId = request.getParameter("roleId");
		paramMap.put("roleId", roleId);
		List<TsRoleMenu> rolemenulist = tsRoleMenuManager.findList(paramMap);
		 
		List<TreeNode> treeNode = toTreeNodeList(dataList , rolemenulist);
		result.put("success", true);
		result.put("data",treeNode);
		outJson(result);
	}
	private List<TreeNode> toTreeNodeList(List<Menu> syteDemos,List<TsRoleMenu> rolemenulist) {
		List<Menu> processList = new ArrayList<Menu>(syteDemos);
		List<TreeNode> rootList = new ArrayList<TreeNode>();
		for (Menu demo : processList) {
			Integer parentId = demo.getFuncPid();
			String url = demo.getFuncUrl();
			if (url == null && parentId == 1) {
				TreeNode node = toTreeNode(demo);
				rootList.add(node);
				syteDemos.remove(node);
			}
		}
		for (TreeNode root : rootList) {
			buildTree(root, syteDemos);
		}
		return rootList;
	}
	private TreeNode toTreeNode(Menu demo) {
		TreeNode node = new TreeNode();
		node.setText(demo.getFuncName());
		node.setId("" + demo.getId());
		node.setState("open");
		return node;
	}
	private void buildTree(TreeNode parent, List<Menu> syteDemos) {
		List<Menu> processList = new ArrayList<Menu>(syteDemos);
		for (Menu demo : processList) {
			String parentId = "" + demo.getFuncPid();
			if (parentId.equals(parent.getId())) {
				List<TreeNode> children = parent.getChildren();
				if (children == null) {
					children = new ArrayList<TreeNode>();
					parent.setChildren(children);
				}
				TreeNode child = toTreeNode(demo);
				child.setParentId(Integer.parseInt(parent.getId()));
				children.add(child);
				syteDemos.remove(demo);
				buildTree(child, syteDemos);
			}
		}
	}

	/**
	 * 修改角色的菜单 
	 * @throws IOException 
	 */
	public void rolemenu() throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			HttpServletRequest request = getRequest();
			String json = request.getParameter("json");
			if (null != json && !"".equals(json)) {
				JSONObject jsonobject = JSONObject.fromObject(json); 
				/** 设置主键值 */
				// menuobj.setId(jsonobject.get("id").toString());
				String roleId = jsonobject.get("roleId").toString();
				String nodes = jsonobject.get("nodes").toString();
				/** 1\ removeByIdArry(TsRoleMenu u*/
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("roleId", roleId);
				tsRoleMenuManager.removeByMap(paramMap);
				String[] ids = StringTool.SplitString(nodes,",");
				for(int i=0;null!=ids&&i<ids.length;i++){
					TsRoleMenu tu = new TsRoleMenu();
					tu.setFuncId(Integer.parseInt(ids[i]));
					tu.setRoleId(Integer.parseInt(roleId));
					tu.setDataStatus(1);
					tsRoleMenuManager.save(tu);
				}
				result.put("success", true);
				result.put("msg", "修改成功!");
			} else {
				result.put("success", false);
				result.put("msg", "修改失败 数据错误!");
			}
		} catch (Exception e) {
			result.put("success", false);
			result.put("msg", "修改失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	
}
